<template>
  <div class="route-planner">
    <!-- 侧边栏：路线规划表单 -->
    <aside class="sidebar">
      <div class="sidebar-content">
        <div class="sidebar-header">
          <h1 class="app-title">路线规划</h1>
          <p class="app-slogan">探索城市美景，规划最佳路线</p>
        </div>

        <el-card class="form-card">
          <div class="form-header">
            <h2 class="form-title">路线规划</h2>
            <div class="form-subtitle">定制你的完美旅程</div>
          </div>

          <el-form label-width="80px">
            <el-form-item label="目的地">
              <div class="destination-wrapper">
                <el-select
                  v-model="selectedPOI"
                  placeholder="请选择景点"
                  filterable
                  clearable
                  size="large"
                >
                  <el-option v-for="poi in pois" :key="poi.id" :label="poi.name" :value="poi" />
                </el-select>
                <i class="location-icon el-icon-location"></i>
              </div>
            </el-form-item>

            <el-form-item label="出行方式">
              <div class="transport-options">
                <el-radio-group v-model="transportMode" size="large">
                  <el-radio-button label="driving">
                    <i class="el-icon-car"></i> 驾车
                  </el-radio-button>
                  <el-radio-button label="walking">
                    <i class="el-icon-location"></i> 步行
                  </el-radio-button>
                  <el-radio-button label="transit">
                    <i class="el-icon-bus"></i> 公交
                  </el-radio-button>
                </el-radio-group>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="planRoute"
                class="plan-button"
                :disabled="!selectedPOI"
                size="large"
              >
                <i class="el-icon-location-outline"></i> 开始规划
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 推荐景点 -->
        <div class="recommended-places">
          <h3 class="section-title">热门景点推荐</h3>
          <div class="place-list">
            <div
              v-for="poi in recommendedPOIs"
              :key="poi.id"
              class="place-item"
              @click="selectRecommendedPlace(poi)"
            >
              <img :src="poi.image" :alt="poi.name" class="place-image" />
              <div class="place-info">
                <h4 class="place-name">{{ poi.name }}</h4>
                <div class="place-rating">
                  <i class="el-icon-star-on"></i>
                  <span>{{ poi.rating }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </aside>

    <!-- 主内容区：地图和路线信息 -->
    <main class="main-content">
      <div class="map-container" ref="mapContainer"></div>

      <!-- 路线信息卡片 -->
      <div v-if="routeInfo" class="route-info-card">
        <div class="route-header">
          <h3 class="route-title">从当前位置到 {{ selectedPOI.name }}</h3>
          <div class="route-summary">
            <div class="route-duration"><i class="el-icon-time"></i> {{ routeInfo.duration }}</div>
            <div class="route-distance">
              <i class="el-icon-location-outline"></i> {{ routeInfo.distance }}
            </div>
          </div>
        </div>

        <div class="route-steps">
          <h4 class="steps-title">路线详情</h4>
          <ul class="steps-list">
            <li v-for="(step, index) in routeInfo.steps" :key="index" class="step-item">
              <div class="step-icon">
                <span class="step-number">{{ index + 1 }}</span>
              </div>
              <div class="step-content">
                <p class="step-instruction">{{ step.instruction }}</p>
                <p class="step-distance">{{ step.distance }}</p>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { POI } from '@/types/poi'

// 状态管理
const pois = ref<POI[]>([])
const selectedPOI = ref<POI | null>(null)
const transportMode = ref('driving')
const mapContainer = ref<HTMLDivElement | null>(null)
const map = ref<any>(null)
const routeInfo = ref<any>(null)

// 模拟推荐景点数据
const recommendedPOIs = computed(() => {
  return pois.value.slice(0, 4)
})

onMounted(async () => {
  try {
    // 加载景点数据
    const res = await fetch('http://localhost:3000/pois')
    pois.value = await res.json()

    // 初始化地图
    initMap()
  } catch (error) {
    ElMessage.error('加载数据失败，请重试')
    console.error(error)
  }
})

function initMap() {
  // 创建地图实例
  map.value = new BMapGL.Map(mapContainer.value!)
  map.value.centerAndZoom(new BMapGL.Point(118.08, 24.45), 13)
  map.value.enableScrollWheelZoom(true)

  // 添加地图控件
  map.value.addControl(new BMapGL.NavigationControl())
  map.value.addControl(new BMapGL.ScaleControl())
  map.value.addControl(new BMapGL.OverviewMapControl())
}

function planRoute() {
  if (!selectedPOI.value) {
    ElMessage.warning('请选择一个目的地')
    return
  }

  const geolocation = new BMapGL.Geolocation()
  geolocation.getCurrentPosition(function (position: any) {
    if (this.getStatus() === BMAP_STATUS_SUCCESS) {
      const start = new BMapGL.Point(position.point.lng, position.point.lat)
      const end = new BMapGL.Point(selectedPOI.value!.lng, selectedPOI.value!.lat)

      // 清除地图覆盖物
      map.value.clearOverlays()

      // 添加起点和终点标记
      const startMarker = new BMapGL.Marker(start, {
        icon: new BMapGL.Icon(
          '//api.map.baidu.com/images/marker_red_sprite.png',
          new BMapGL.Size(23, 25),
        ),
      })
      const endMarker = new BMapGL.Marker(end, {
        icon: new BMapGL.Icon(
          '//api.map.baidu.com/images/marker_blue_sprite.png',
          new BMapGL.Size(23, 25),
        ),
      })

      map.value.addOverlay(startMarker)
      map.value.addOverlay(endMarker)
      map.value.setViewport([start, end])

      // 根据选择的交通方式规划路线
      let route
      switch (transportMode.value) {
        case 'driving':
          route = new BMapGL.DrivingRoute(map.value, {
            renderOptions: { map: map.value, autoViewport: true },
            onSearchComplete: function (results: any) {
              if (route.getStatus() === BMAP_STATUS_SUCCESS) {
                const plan = results.getPlan(0)
                formatRouteInfo(plan)
              }
            },
          })
          break
        case 'walking':
          route = new BMapGL.WalkingRoute(map.value, {
            renderOptions: { map: map.value, autoViewport: true },
            onSearchComplete: function (results: any) {
              if (route.getStatus() === BMAP_STATUS_SUCCESS) {
                const plan = results.getPlan(0)
                formatRouteInfo(plan)
              }
            },
          })
          break
        case 'transit':
          route = new BMapGL.TransitRoute(map.value, {
            renderOptions: { map: map.value, autoViewport: true },
            onSearchComplete: function (results: any) {
              if (route.getStatus() === BMAP_STATUS_SUCCESS) {
                const plan = results.getPlan(0)
                formatRouteInfo(plan)
              }
            },
          })
          break
      }

      // 开始搜索路线
      route?.search(start, end)
    } else {
      ElMessage.error('定位失败，请手动输入起点')
    }
  })
}

// 格式化路线信息
function formatRouteInfo(plan: any) {
  const distance = formatDistance(plan.getDistance(true))
  const duration = formatDuration(plan.getDuration(true))

  // 提取路线步骤
  const steps = []
  for (let i = 0; i < plan.getNumRoutes(); i++) {
    const route = plan.getRoute(i)
    for (let j = 0; j < route.getNumSteps(); j++) {
      const step = route.getStep(j)
      steps.push({
        instruction: step.getDescription(),
        distance: formatDistance(step.getDistance()),
      })
    }
  }

  // 更新路线信息
  routeInfo.value = {
    distance,
    duration,
    steps,
  }
}

// 格式化距离
function formatDistance(meters: number): string {
  if (meters < 1000) {
    return `${meters} 米`
  } else {
    return `${(meters / 1000).toFixed(1)} 公里`
  }
}

// 格式化时间
function formatDuration(seconds: number): string {
  const minutes = Math.floor(seconds / 60)
  if (minutes < 60) {
    return `${minutes} 分钟`
  } else {
    const hours = Math.floor(minutes / 60)
    const remainingMinutes = minutes % 60
    return `${hours} 小时 ${remainingMinutes} 分钟`
  }
}

// 选择推荐景点
function selectRecommendedPlace(poi: POI) {
  selectedPOI.value = poi
}
</script>

<style scoped>
/* 全局样式 */
.route-planner {
  display: flex;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 侧边栏样式 */
.sidebar {
  width: 380px;
  background-color: #fff;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
  z-index: 10;
  overflow-y: auto;
  transition: width 0.3s ease;
}

.sidebar-content {
  padding: 30px;
}

.sidebar-header {
  text-align: center;
  margin-bottom: 30px;
}

.app-title {
  font-size: 28px;
  font-weight: 600;
  color: #165dff;
  margin-bottom: 10px;
}

.app-slogan {
  font-size: 16px;
  color: #86909c;
}

.form-card {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
  margin-bottom: 30px;
  overflow: hidden;
}

.form-header {
  background-color: #165dff;
  color: white;
  padding: 10px 20px;
  text-align: center;
}

.form-title {
  font-size: 22px;
  font-weight: 500;
  margin-bottom: 5px;
}

.form-subtitle {
  font-size: 14px;
  opacity: 0.8;
}

.destination-wrapper {
  position: relative;
}

.location-icon {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #165dff;
  font-size: 18px;
}

.el-select .el-input__inner {
  padding-left: 40px !important;
  border-radius: 10px !important;
  height: 48px !important;
  border-color: #e4e7ed !important;
}

.el-select .el-input__inner:focus {
  border-color: #165dff !important;
}

.transport-options .el-radio-button__inner {
  padding: 12px 20px !important;
  border-radius: 8px !important;
  margin-right: 10px !important;
  background-color: #f5f7fa !important;
  border-color: #e4e7ed !important;
  color: #606266 !important;
}

.transport-options .el-radio-button__inner:hover {
  color: #165dff !important;
}

.transport-options .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  background-color: #165dff !important;
  border-color: #165dff !important;
  color: white !important;
  box-shadow: -1px 0 0 0 #165dff !important;
}

.plan-button {
  width: 100%;
  height: 50px;
  border-radius: 10px;
  font-size: 18px;
  background-color: #165dff;
  border: none;
  transition: all 0.3s ease;
}

.plan-button:hover {
  background-color: #0e42d2;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(22, 93, 255, 0.3);
}

.plan-button:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 推荐景点样式 */
.recommended-places {
  margin-top: 30px;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: '';
  width: 4px;
  height: 18px;
  background-color: #165dff;
  margin-right: 8px;
  border-radius: 2px;
}

.place-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 15px;
}

.place-item {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 10px;
  padding: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.place-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.place-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 15px;
}

.place-info {
  flex: 1;
}

.place-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
}

.place-rating {
  display: flex;
  align-items: center;
  color: #ff9900;
  font-size: 14px;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
}

.map-container {
  flex: 1;
  height: 100%;
  width: 100%;
}

/* 路线信息卡片 */
.route-info-card {
  position: absolute;
  bottom: 20px;
  left: 20px;
  right: 20px;
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  padding: 20px;
  max-height: 300px;
  overflow-y: auto;
  transition: all 0.3s ease;
  transform: translateY(0);
  opacity: 1;
}

.route-info-card.hidden {
  transform: translateY(100%);
  opacity: 0;
  pointer-events: none;
}

.route-header {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.route-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 10px;
}

.route-summary {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #606266;
}

.route-duration,
.route-distance {
  display: flex;
  align-items: center;
}

.route-duration i,
.route-distance i {
  margin-right: 5px;
  color: #165dff;
}

.steps-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 10px;
}

.steps-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.step-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #f5f7fa;
}

.step-item:last-child {
  border-bottom: none;
}

.step-icon {
  margin-right: 15px;
}

.step-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background-color: #165dff;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  font-weight: 500;
}

.step-instruction {
  font-size: 14px;
  color: #303133;
  margin-bottom: 5px;
}

.step-distance {
  font-size: 12px;
  color: #909399;
}

/* 响应式布局 */
@media (max-width: 1024px) {
  .sidebar {
    width: 320px;
  }

  .sidebar-content {
    padding: 20px;
  }

  .app-title {
    font-size: 24px;
  }

  .app-slogan {
    font-size: 14px;
  }
}

@media (max-width: 768px) {
  .route-planner {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
    height: auto;
    overflow-y: visible;
  }

  .main-content {
    min-height: 500px;
  }

  .route-info-card {
    bottom: 10px;
    left: 10px;
    right: 10px;
    padding: 15px;
  }
}
</style>
